package com.example.jucsample.cb;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author zhenwei.wu
 * @date 2021/3/17
 */
public class AsyncNotify {

    public static void main(String[] args) {
        // 最后一个到达的线程，执行完command后唤醒所有线程
        int p = 3;
        CyclicBarrier cb = new CyclicBarrier(p, () -> {
            System.out.println("notify client");
        });
        for (int i = 0; i < p; i++) {
            final int n = i;
            new Thread(() -> {
                try {
                    Random random = new Random();
                    Thread.sleep(random.nextInt(6) * 1000);
                    System.out.println(String.format("Thread-%s running", n));
                    cb.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }

    }

}
